﻿using CBLibrary.JwtBearer.BootStrapper;
using CBLibrary.JwtBearer.IService;
using CBLibrary.JwtBearer.JwtProvider;
using CBLibrary.JwtBearer.Model;
using CBLibrary.Repository.BootStrapper;
using CBLibrary.Repository.Cache;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;
using RepositoryTestWeb.AppService.Authorization;
using RepositoryTestWeb.BootStrapper;
using RepositoryTestWeb.DbContext;
using Swashbuckle.AspNetCore.Swagger;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace RepositoryTestWeb
{
    public class Startup
    {
        private IConfiguration Configuration { get; }

        private JwtProviderOption JwtProviderOption { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            var jwtBearer = Configuration.GetSection("Authentication:JwtBearer");
            int.TryParse(jwtBearer["ExpirationIn"], out var expirationIn);

            JwtProviderOption = new JwtProviderOption
            {
                Path = jwtBearer["Path"],
                Audience = jwtBearer["Audience"],
                Issuer = jwtBearer["Issuer"],
                SecurityKey = jwtBearer["SecurityKey"],
                ExpirationIn = expirationIn
            };
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Title = "WebApi", Version = "v1" });

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", Enumerable.Empty<string>() }
                });
            });

            //注入 DbContext
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            services.AddDbContext<TestDbContext>(option =>
                option.UseMySql(Configuration["Database:MYSQLConnectionString"],
                    builder => builder.MigrationsAssembly(migrationsAssembly)));

            services.AddDbContext<Microsoft.EntityFrameworkCore.DbContext, TestDbContext>();


            //注入 HttpContext
            services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, HttpContextAccessor>();

            //注入 仓储
            services.AddRepository();

            //注入 实体映射
            services.AddAutoMapper();

            //注入 应用服务
            services.AddAppService();

            #region CBLibrary.JwtBearer
            //注入 JwtTokenProvider
            services.AddScoped(typeof(JwtTokenProvider));

            //注入 JwtService
            services.AddJwtService(JwtProviderOption);

            //注入 自定义认证服务
            services.AddScoped<IAuthorizationService, AuthorizationService>();
            #endregion

            //注册 CacheService
            services.AddMemoryCache();
            services.AddSingleton<ICacheService, MemoryCacheProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi V1");
                });
            }


            // 数据库初始化
            app.InitializeDatabase();

            // NLog
            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");

            #region CBLibrary.Repository
            // 数据库初始化
            app.InitializeDatabase();
            #endregion

            #region CBLibrary.JwtBearer
            // 启用认证
            app.UseAuthentication(JwtProviderOption);
            #endregion


            app.UseMvc();
        }
    }
}
